package com.reebake.ideal.infra.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.reebake.ideal.infra.entity.Region;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

@Service
@Primary
public class RegionServicePlusImpl extends RegionServiceImpl {
    public static final String ROOT_ID = "0";
    public static final String ROOT_NAME = "根";

    private void notLeaf(String regionId) {
        LambdaUpdateWrapper<Region> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(Region::getIsLeaf, false).eq(Region::getRegionId, regionId).eq(Region::getIsLeaf, true);
        super.update(updateWrapper);
    }

    @Override
    public boolean saveOrUpdate(Region entity) {
        String parentId = entity.getParentId();
        String id = entity.getRegionId();
        if(StrUtil.isNotBlank(parentId) && !ROOT_ID.equals(parentId)) {
            Region parent = getById(parentId);
            entity.setParentName(parent.getRegionName());
        }
        if((StrUtil.isBlank(parentId) || ROOT_ID.equals(parentId))
        && StrUtil.isBlank(entity.getRegionId())) {
            entity.setParentId(ROOT_ID);
            entity.setParentName(ROOT_NAME);
        }
        boolean result = super.saveOrUpdate(entity);
        if(result && !ROOT_ID.equals(parentId)) {
            notLeaf(parentId);
        }
        return result;
    }
}
